import 'dart:async';

import 'package:enterprise_v6_app/app/components/video/video_play_widget.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/custom_event_bus.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/couser_center/textbook_detail_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/education/course_center/integrated_theme/course_detail_detail_page/course_detail/train_directory/train_directory_controller.dart';

/// 课程详情详情
class CourseDetailDetailPageController extends GetxController {
  /// 创建一个全局的 ScrollController
  ScrollController myScrollController = ScrollController();
  final GlobalKey<VideoPlayWidgetState> videoKey = GlobalKey();

  /// 查询课程详情
  TextbookDetailEntity? textbookDetailEntity;

  /// 初始页面设置 [initPage] 0: 1：
  int initPage = 0;

  StreamSubscription<MyEntity>? eventSubscription;

  ///视频播放的Url Interface.fileUrl https://www.runoob.com/try/demo_source/movie.mp4
  String directoryFile = ''; //目录资源xxx.mp4
  String directoryFileId = ''; //目录id
  String planId = '';

  Duration? totalDurationInSeconds;
  Duration? currentPositionDurationInSeconds;

  @override
  void onInit() {
    super.onInit();
    if (Get.arguments['planId'] != null) {
      planId = Get.arguments['planId'] as String;
    }

    //查询课程详情
    textbookDetail();
    //接受事件
    eventSubscription = CustomEventBus.getInstance().on<MyEntity>().listen((event) {
      if (event.type == MyEntity.TYPEDIRECTORYFILE) {
        directoryFile = event.data as String;
        ///_videoPlayerController?.dispose(); 会在创建新实例之前释放之前的实例。
        ///这样可以确保在创建新的 VideoPlayerController 之前，之前的资源已经被正确地释放。
        videoKey.currentState?.disVideoPlayerController();
        videoKey.currentState?.init(directoryFile);
        update();
      } else if (event.type == MyEntity.TYPEDIRECTORYFILEID) {
        directoryFileId = event.data as String;
      } else if (event.type == MyEntity.DEADLINE) {
        //设置视频进度
        final int deadline = event.data as int;
        Future.delayed(const Duration(seconds: 1), () {
          videoKey.currentState?.seekToWhenReady(deadline);
        });
      }
    });

    //对directoryFile 可能需要赋值 外面选中了 设置url  目录下选中表示
    if (Get.arguments['directoryFile'] != null) {
      directoryFile = Get.arguments['directoryFile'] as String;
    }
  }
  ///当控制器被销毁时调用，可以在这里执行清理逻辑，比如关闭流或取消订阅。
  @override
  void onClose() {
    super.onClose();
    //视频时长测试--
    // Duration? totalDuration = videoKey.currentState?.totalDuration();
    // Duration? currentPositionDuration = videoKey.currentState?.currentPositionDuration();
    // print('总时长：${totalDuration?.inSeconds} 秒');
    // print('当前播放进度：${currentPositionDuration?.inSeconds} 秒');
    //界面销毁 新增课程观看记录调用（告诉后端这里的用户观看后的总时长和观看进度）
    if (totalDurationInSeconds?.inSeconds != null && currentPositionDurationInSeconds?.inSeconds != null) {
      addCourseWatchRecord(totalDurationInSeconds?.inSeconds, currentPositionDurationInSeconds?.inSeconds);
    }
    //取消EventBus事件订阅，防止内存泄漏。
    eventSubscription?.cancel();
  }

  ///新增课程观看记录
  void addCourseWatchRecord(int? totalDurationInSeconds, int? currentPositionDurationInSeconds) async {
    final res = await HttpUtil().generatePostRequest(Interface.addCourseWatchRecord, data: {
      'textbookId': Get.arguments['id'], //	课程id
      'totalDuration': totalDurationInSeconds, //总时长
      'deadline': currentPositionDurationInSeconds, //截至时间(观看进度)
      'directoryId': directoryFileId, //课程目录id（下个界面发过来的）
      'planId': planId, //计划id (上上个界面传入)
    }).execute();
    res.onSuccess((result) {
      Get.find<TrainDirectoryController>().onInit();
      //刷新界面
      CustomEventBus.getInstance().fire(MyEntity(MyEntity.TYPGETPLANBYTEXTBOOKID, ''));
    });
  }

  ///查询课程详情
  void textbookDetail() async {
    final res = await HttpUtil().generateGetRequest<TextbookDetailEntity>(
      Interface.textbookDetail,
      queryParameters: {
        'textbookId': Get.arguments['id'],
      },
    ).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        textbookDetailEntity = result.data!;
        update();
      }
    });
  }
}
